package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.message.MessageConstant;
import com.itheima.message.RedisConstant;
import com.itheima.pojo.Setmeal;
import com.itheima.querypage.QueryPageBean;
import com.itheima.results.PageResult;
import com.itheima.results.Result;
import com.itheima.service.SetmealService;
import com.itheima.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    //上传图片
    @RequestMapping("/upload.do")
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile) {
        //获得文件的原始文件名
        String originalFilename = imgFile.getOriginalFilename();
        //取得文件最后一个"." 的索引
        int index = originalFilename.lastIndexOf(".");
        //截取 获得后缀 .jpg
        String string = originalFilename.substring(index);
        //随机生成一个 文件名 拼接上后缀 .jpg
        String filename = UUID.randomUUID().toString() + string;
        try {
            //将文件上传到七牛服务器
            QiniuUtils.upload2Qiniu(imgFile.getBytes(), filename);
            Jedis resource = jedisPool.getResource();
            resource.sadd(RedisConstant.SETMEAL_PIC_RESOURCES, filename);
            //记得关闭资源
            resource.close();
        } catch (IOException e) {
            e.printStackTrace();
            //上传失败
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }
        //上传成功
        return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS, filename);
    }

    @Reference
    private SetmealService setmealService;

    //使用JedisPool操作Redis服务
    @Autowired
    private JedisPool jedisPool;

    //分页查询
    @RequestMapping("/findPage.do")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        return setmealService.findPage(queryPageBean);
    }

    //添加套餐数据
    @RequestMapping("/add.do")
    public Result add(@RequestBody Setmeal setmeal, Integer[] checkgroupIds) {
        try {
            setmealService.add(setmeal, checkgroupIds);
        } catch (Exception e) {
            e.printStackTrace();
            //新增失败
            return new Result(false, MessageConstant.ADD_SETMEAL_FAIL);
        }
        return new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);
    }
}
